﻿using System;
using System.Collections.ObjectModel;
using System.Data.Entity;
using System.Linq;
using System.Web.Mvc;
using EntityFramework.Extensions;
using Pyramid.Models;

namespace Pyramid.Controllers
{
	public class PerformanceController : BaseController
	{
		public ActionResult Manage(int? year, int? month)
		{
			var date = DateTime.Now.AddMonths(-1);
			var y = year ?? date.Year;
			var m = month ?? date.Month;
			if (y >= date.Year && m > date.Month)
			{
				ViewBag.Master = new PerformanceMaster { Year = y, Month = m };
				ViewBag.HasError = true;
				ViewBag.Message = string.Format("选择的月份不能晚于{0:yyyy年M月}，请重新选择！", date);
				return View();
			}

			var model = Db.PerformanceMasters
				.Include(x => x.PerfomanceDetails.Select(s => s.Staff.Position))
				.Include(x => x.PerfomanceDetails.Select(s => s.Staff.Department))
				.FirstOrDefault(x => x.Year == y && x.Month == m) ?? new PerformanceMaster
				{
					Year = y,
					Month = m,
					PerfomanceDetails = Db.Staves.Include(x => x.Position)
						.Include(x => x.Department)
						.ToList()
						.Select(x => new PerformanceDetail
						{
							Score = 0,
							StaffId = x.Id,
							Staff = x
						}).ToList(),
					CreateTime = DateTime.Now,
					CreateUserId = User.UserId,
					Status = (int)DataStatus.New
				};
			ViewBag.HasError = false;
			ViewBag.Master = model;
			return View();
		}

		[HttpPost]
		public ActionResult Edit(int id, FormCollection collection)
		{
			var master = new PerformanceMaster
			{
				CreateUserId = User.UserId,
				EditUserId = User.UserId,
				CreateTime = DateTime.Now,
				EditTime = DateTime.Now
			};
			if (id > 0)
			{
				master = Db.PerformanceMasters.Single(x => x.Id == id);
			}

			if (!TryUpdateModel(master)) return JError();
			var details = collection.AllKeys
				.Where(x => x.StartsWith("score_"))
				.Select(key => new PerformanceDetail
				{
					StaffId = Convert.ToInt32(key.Substring("score_".Length)),
					Score = Convert.ToInt32(collection[key])
				}).ToList();

			master.PerfomanceDetails = new Collection<PerformanceDetail>(details);

			if (master.Id > 0)
			{
				//delete details
				Db.PerfomanceDetails.Delete(x => x.MasterId == master.Id);

				master.EditUserId = User.UserId;
				master.EditTime = DateTime.Now;
			}
			else
			{
				Db.PerformanceMasters.Add(master);
			}

			Db.SaveChanges();

			return JSuccess();
		}
	}
}